package controllers

import (
	"autoPage/models"
	"errors"
	"github.com/astaxie/beego"
	"github.com/wxnacy/wgo/arrays"
	"time"

	"github.com/pquerna/ffjson/ffjson"
	"strconv"
	"strings"
)

type ListConfigController struct {
	BaseController
}

func (dc *ListConfigController) URLMapping() {
	dc.Mapping("List", dc.List)
	dc.Mapping("Add", dc.Add)
	dc.Mapping("Edit", dc.Edit)
	dc.Mapping("ClearCache", dc.ClearCache)
	dc.Mapping("Reset", dc.Reset)
}
func (dc *ListConfigController) Reset() {
	models.ClearCache()
	algoInfo := beego.AppConfig.String("SysInfo::algoInfo")
	algo_port := beego.AppConfig.String("SysInfo::algo_port")
	host_dir := beego.AppConfig.String("SysInfo::host_dir")
	algo_start_cmd := beego.AppConfig.String("SysInfo::algo_start_cmd")
	algo_start_envs := beego.AppConfig.String("SysInfo::algo_start_envs")

	var errarr []string
	sql := "update page_config set configJson = '" + algoInfo + "' ,configId = 'AlgoInfo' where id =11"
	err := dc.ExecuteNoquery(allinkstr, sql)
	if err != nil {
		errarr = append(errarr, err.Error())
		beego.Error("update page_config AlgoInfo failed: ", err.Error())
	} else {
		beego.Info("update page_config AlgoInfo success")
	}
	sql = "update page_config set configJson = '" + algo_port + "' ,configId = 'algo_port' where id =10"
	err = dc.ExecuteNoquery(allinkstr, sql)
	if err != nil {
		errarr = append(errarr, err.Error())
		beego.Error("update page_config algo_port failed: ", err.Error())
	} else {
		beego.Info("update page_config algo_port success")
	}
	sql = "update page_config set configJson = '" + host_dir + "' ,configId = 'host_dir' where id =9"
	err = dc.ExecuteNoquery(allinkstr, sql)
	if err != nil {
		errarr = append(errarr, err.Error())
		beego.Error("update page_config host_dir failed: ", err.Error())
	} else {
		beego.Info("update page_config host_dir success")
	}

	sql = "update page_config set configJson = '" + algo_start_cmd + "' ,configId = 'algo_start_cmd' where id =8"
	err = dc.ExecuteNoquery(allinkstr, sql)
	if err != nil {
		errarr = append(errarr, err.Error())
		beego.Error("update page_config algo_start_cmd failed: ", err.Error())
	} else {
		beego.Info("update page_config algo_start_cmd success")
	}

	sql = "update page_config set configJson = '" + algo_start_envs + "' ,configId = 'algo_start_envs' where id =7"
	err = dc.ExecuteNoquery(allinkstr, sql)
	if err != nil {
		errarr = append(errarr, err.Error())
		beego.Error("update page_config algo_start_envs failed: ", err.Error())
	} else {
		beego.Info("update page_config algo_start_envs success")
	}
	if len(errarr) > 0 {
		dc.ShowMsg("执行失败，"+strings.Join(errarr, "；"), "-1", 4)

	} else {
		dc.ShowMsg("数据初始化成功", "-1", 2)

	}
}
func (dc *ListConfigController) ClearCache() {
	err := models.ClearCache()
	if err == nil {
		dc.ShowMsg("删除成功！", "/pageconfig/list", 1)
	} else {
		dc.ShowMsg("删除成功！", "/pageconfig/list", 1)
	}
}



func (dc *ListConfigController) List() {
	fields := []string{"id", "configId", "configJson", "createtime",
		"lastmodifytime"}
	l, err := models.GetAllPageConfig(fields)
	if err != nil {
		dc.Data["list"] = nil
	} else {
		dc.Data["list"] = l
	}
	dc.Data["CurrentMenu"] = PAGECONFIG_MENU
	dc.Data["ActiveMenu"] = PAGECONFIG_MENU
	dc.TplName = "pageconfig/list.html"
}

func (dc *ListConfigController) Edit() {
	if dc.IsSubmit() {
		var e models.PageConfig
		var F models.ConfigItems
		if err := dc.ParseForm(&F); err != nil {
			dc.ShowMsg("修改表单失败，请重试!", "-1", 4)
			beego.Error("修改表单失败,", err.Error())
		} else {
			queryParams := dc.GetUrlQuery()
			e.Id, _ = strconv.ParseInt(queryParams.Get("id"), 10, 64)
			e.ConfigId = dc.Ctx.Request.Form["configId"][0]
			e.LastModifyTime = time.Now().Format(timefmt)

			var jsonArr []map[string]interface{}
			var fieldArr []string
			for i := 0; i < len(F.Field); i++ {
				m := make(map[string]interface{})
				if F.Field != nil {
					if arrays.Contains(fieldArr, F.Field[i]) >= 0 {
						err = errors.New("字段 " + F.Field[i] + "重复，请修改后重新提交")
						dc.ShowMsg("字段 "+F.Field[i]+"重复，请修改后重新提交", "-1", 4)
						beego.Error("字段 " + F.Field[i] + "重复，请修改后重新提交")
						return
					}
					fieldArr = append(fieldArr, F.Field[i])
					m["field"] = F.Field[i]
				}
				if F.Type != nil {
					m["type"] = F.Type[i]
				}
				if F.Name != nil {
					m["name"] = F.Name[i]
				}
				if F.Options != nil {
					if strings.TrimSpace(F.Options[i]) != "" {
						m["options"] = F.Options[i]
					}
				}
				if F.AllowBlank != nil {
					m["allowblank"] = F.AllowBlank[i]
				}
				if F.ReadOnly != nil {
					m["readonly"] = F.ReadOnly[i]
				}
				if F.MaxLength != nil {
					if strings.TrimSpace(strconv.Itoa(F.MaxLength[i])) != "" {
						m["maxlength"] = F.MaxLength[i]
					}
				}
				if F.Width != nil {
					if strings.TrimSpace(F.Width[i]) != "" {
						m["width"] = F.Width[i]
					}
				}
				if F.Height != nil {
					if strings.TrimSpace(F.Height[i]) != "" {
						m["height"] = F.Height[i]
					}
				}
				jsonArr = append(jsonArr, m)
			}
			jsonbytes, err := ffjson.Marshal(jsonArr)
			if err != nil {
				beego.Error("编辑失败，错误信息:", err.Error())
				dc.ShowMsg("修改失败了", "/pageconfig/list", 3)
			} else {
				e.ConfigJson = string(jsonbytes)
				err := models.UpdatePageConfigById(&e)
				if err != nil {
					beego.Error("pageconfig ：", err.Error())
					dc.ShowMsg("修改失败了", "/pageconfig/list", 1)
				} else {
					dc.ShowMsg("修改成功了", "/pageconfig/list", 1)
				}
			}
		}
	} else {
		_, actionName := dc.GetControllerAndAction()
		dc.Data["ACTION_NAME"] = actionName
		var id int64

		queryParams := dc.GetUrlQuery()
		id, _ = strconv.ParseInt(queryParams.Get("id"), 10, 64)

		data, _ := models.GetPageConfigById(id)
		var m []map[string]interface{}
		ffjson.Unmarshal([]byte(data.ConfigJson), &m)

		dc.Data["JsonArr"] = m
		dc.Data["CurrentMenu"] = PAGECONFIG_MENU
		dc.Data["ActiveMenu"] = PAGECONFIG_MENU

		dc.Data["Data"] = data
		dc.TplName = "pageconfig/form.html"
	}
}

//添加
func (dc *ListConfigController) Add() {
	if dc.IsSubmit() {

	} else {
		_, actionName := dc.GetControllerAndAction()
		dc.Data["ACTION_NAME"] = actionName
		dc.Data["CurrentMenu"] = LISTCONFIG_MENU
		dc.TplName = "listconfig/form.html"
	}
}
